//
//  GRAliPushManager.m
//  YC_GRice
//
//  Created by Feng Liu on 2018/9/12.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRAliPushManager.h"
#import <CloudPushSDK/CloudPushSDK.h>
#import <AVFoundation/AVFoundation.h>
#import "BDSSpeechSynthesizer.h"

@interface GRAliPushManager ()

@end


@implementation GRAliPushManager

+ (instancetype)defaultManager {
    static GRAliPushManager *pushManager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pushManager = [[GRAliPushManager alloc] init];
    });
    
    return pushManager;
}

- (void)registerAliPush:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 注册APNS, 获取deviceToken并上报
    [self registerAPNS:application];
    // 初始化SDK
    [self initCloudSDK];
    // 点击通知将App从关闭状态启动时，将通知打开回执上报
    [CloudPushSDK sendNotificationAck:launchOptions];
    
    // 百度语音合成
    [self BDSpeechClient];
}

- (void)BDSpeechClient {
    [[BDSSpeechSynthesizer sharedInstance] setApiKey:BAIDUKEY withSecretKey:BDSECRETKEY];
    
    [[BDSSpeechSynthesizer sharedInstance] setAudioSessionCategory:AVAudioSessionCategoryPlayback];
    
    // 在这里选择不同的离线音库（请在XCode中Add相应的资源文件），同一时间只能load一个离线音库。根据网络状况和配置，SDK可能会自动切换到离线合成。
    NSString* offlineEngineSpeechData = [[NSBundle mainBundle] pathForResource:@"Chinese_And_English_Speech_Female" ofType:@"dat"];
    
    NSString* offlineChineseAndEnglishTextData = [[NSBundle mainBundle] pathForResource:@"Chinese_And_English_Text" ofType:@"dat"];
    
    [[BDSSpeechSynthesizer sharedInstance] loadOfflineEngine:offlineChineseAndEnglishTextData speechDataPath:offlineEngineSpeechData licenseFilePath:nil withAppCode:BAIDUAPPID];
}


- (void)registerAPNS:(UIApplication *)application {
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
        notificationCenter.delegate                          = self;
//        [self createCustomNotificationCategory:notificationCenter];
        if (@available(iOS 12.0, *)) {
            [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionProvisional completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    NSLog(@"User authored notification.");
                    // 向APNs注册，获取deviceToken
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [application registerForRemoteNotifications];
                    });
                }else {
                    NSLog(@"User denied notification.");
                }
            }];
        }else {
            [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    NSLog(@"User authored notification.");
                    // 向APNs注册，获取deviceToken
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [application registerForRemoteNotifications];
                    });
                }else {
                    NSLog(@"User denied notification.");
                }
            }];
        }
    } else {
        // Fallback on earlier versions
        [application registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [application registerForRemoteNotifications];
    }
}

- (void)initCloudSDK {
    [CloudPushSDK autoInit:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"push sdk init success，deviceId is %@", [CloudPushSDK getDeviceId]);
        }else {
            NSLog(@"push sdk init fail，error is %@", res.error);
        }
    }];
}

- (void)createCustomNotificationCategory:(UNUserNotificationCenter *)notificationCenter  API_AVAILABLE(ios(10.0)){
    // 自定义`action1`和`action2`
    UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"取消" options: UNNotificationActionOptionNone];
    
    UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"查看" options: UNNotificationActionOptionNone];
    // 创建id为`test_category`的category，并注册两个action到category
    // UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
    UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"action_category" actions:@[action1, action2] intentIdentifiers:@[] options:
                                        UNNotificationCategoryOptionCustomDismissAction];
    // 注册category到通知中心
    [notificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
}


#pragma Mark --------------  监听代理  ----------------
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [CloudPushSDK sendNotificationAck:userInfo];
        [self onMessageReceived:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [CloudPushSDK sendNotificationAck:userInfo];
        [self onMessageReceived:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}


-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if (IOSVERSON < 10.0) {
        [CloudPushSDK sendNotificationAck:userInfo];
        [self onMessageReceived:userInfo];
    }else {
        if (application.applicationState != UIApplicationStateActive) {
            [CloudPushSDK sendNotificationAck:userInfo];
            [self onMessageReceived:userInfo];
        }
    }

    completionHandler(UIBackgroundFetchResultNewData);
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken {
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"did register success");
        }else {
            NSLog(@"register fail with error : %@",res.error);
        }
    }];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error : %@",error);
}

#pragma MARK -------------    通知消息处理   ------------
- (void)onMessageReceived:(NSDictionary *)userInfo {
    NSLog(@"userInfo = %@",userInfo);

    NSDictionary *aps = userInfo[@"aps"];
    if (aps[@"content-available"] && [aps[@"content-available"] boolValue]) {
        NSString *actiontype = userInfo[@"action_type"];
        if ([actiontype isEqualToString:@"one_pay_notify"] && IOSVERSON < 10.0) {
            NSString *content = userInfo[@"content"];
            [[BDSSpeechSynthesizer sharedInstance] speakSentence:content withError:nil];
        }
    }else {
        
    }
}



@end
